import SlsWebLogger from 'js-sls-logger'
import { UUid, createSessionId } from './tools'
let userAgent = require('user-agent')

const CACHE_DEVICE_ID = '__wt_device_id'
const CACHE_USER_ID = '__wt_user_id'
const CACHE_FIRST_DAY = '__wt_first_day'
const CACHE_SESSION_ID = '__wt_session_id'
const CACHE_SESSION_Time = '__wt_session_time'

// 全局变量，多Tracking实例共享
let sessionId, sessionTime;
let firstDay, deviceId, userId;

// 单次会话参数
function initSessionId() {
  sessionId = sessionStorage.getItem(CACHE_SESSION_ID) || createSessionId()
  sessionStorage.setItem(CACHE_SESSION_ID, sessionId)
  sessionTime = sessionStorage.getItem(CACHE_SESSION_Time) || Date.now()
  sessionStorage.setItem(CACHE_SESSION_Time, sessionTime)
}

// 用户缓存数据
function initUserId() {
  const createUUid = UUid()
  deviceId = localStorage.getItem(CACHE_DEVICE_ID) || createUUid()
  localStorage.setItem(CACHE_DEVICE_ID, deviceId)
  firstDay = localStorage.getItem(CACHE_FIRST_DAY) || Date.now()
  localStorage.setItem(CACHE_FIRST_DAY, firstDay)
}

// 上报必传字段
function getExtraData() {
  !firstDay && initUserId()
  !sessionId && initSessionId()
  // refrerer
  let latestReferrer = window.document.referrer || ''
  let latestReferrerHost
  const matchHost = latestReferrer.match(/https?:\/\/([^/:]+)/)
  if (latestReferrer && matchHost && matchHost[1] !== window.location.hostname) {
    latestReferrerHost = matchHost ? matchHost[1] : ''
  }
  return {
    title: document.title,
    url: location.href,
    timestamp: Date.now(),
    userAgent: userAgent.parse(navigator.userAgent),
    latestReferrer,
    latestReferrerHost,
    sessionId,
    sessionTime,
    firstDay,
    userId: userId || deviceId,
  }
}

class Tracking {
  constructor(host, project, logstore) {
    this.host = host
    this.project = project
    this.logstore = logstore
    this.logger = new SlsWebLogger({
      host,      
      project,
      logstore,
      time: 5,
    })
  }
  send(data = {}) {
    const extraData = getExtraData()
    const log = { ...extraData, ...data }
    // 对象的值不能是数字
    // value必须是字符串不能是对象 阿里云要求
    for (let key in log) {
      if (typeof log[key] === 'number') {
        log[key] = String(log[key])
      }else if (typeof log[key] === 'object') {
        log[key] = JSON.stringify(log[key])
      }
    }
    this.logger.send(log)
  }
  login(loginId) {
    if (loginId) {
      userId = loginId
      localStorage.setItem(CACHE_USER_ID, loginId)
    }
  }
}

// 创建埋点实例
let trackerCache = null
function tracker(host, project, logstore) {
  if (trackerCache) {
    return trackerCache
  }
  if (!host || !project || !logstore) {
    throw new Error('未初始化 wt, 请先调用 initTracker()')
  }
  trackerCache = new Tracking(host, project, logstore)
  return trackerCache
}
// 初始化埋点参数并将实例放入全局
function initTracker (host, project, logstore) {
  return tracker(host, project, logstore)
}

export {
  initTracker,
  tracker,
}